<template>
	<view style="width: 100vw;">
		<hx-navbar title="生图描述" :back="true" :fixedWhiteStyle="true" :fixed="false" :color="kblackColor" barPlaceholder="hidden"
			transparent="auto">
		</hx-navbar>
			<!-- #ifdef APP-PLUS -->
			<view class="statusbox"></view>
			<!-- #endif -->
		<view class="">
			<view class="" style="text-align: center;margin: 20rpx auto;">
				<image :src="themeImage" style="background: #EEEEEE;border-radius: 10rpx;border: 3px solid #7655D5;width: 666rpx;height:521rpx;border-radius: 10rpx;" mode=""></image>
				<view style="width: 688rpx;font-weight: 500;font-size: 24rpx;text-align: left;color: #000000;opacity: 0.4;margin: 18rpx auto;"> {{motifDescription}}
				</view>
			</view>
			<view class="" style="display: flex;width: 690rpx;margin:40rpx auto 30rpx;">
				<view class="name_mess display-between" >
				<view class="">画面描述(必填)</view> <view>{{describe.length}}/120</view>
				</view>
			</view>
			<textarea v-model="describe" maxlength='120'
				placeholder='请输入您想要的图片内容或者关键词，如，杰作，一个女孩，单人，完美的眼睛，精致的脸精致的皮肤，灰色的头发，长发，城市，街道酒店，摩天大楼......'
				class="text_class" @blur="bindTextAreaBlur" />
		</view>

		<view class="name_mess fengge mage10" style="display: flex;align-items: center;">
			风格
			<view @click="toggleShowAll">
				<image v-if='showAiImg' class="styIcon" src="@/static/ai/top_icon.png" mode=""></image>
				<image v-else class="styIcon" src="@/static/ai/botton_icon.png" mode=""></image>
				<!-- {{ showAiImg ? '收起' : '显示全部' }}  -->
			</view>
		</view>
		<view class="style mage10">

			<view v-for="(item, index) in listDataToShow">
				<view class="" :class="[{sel:index== Flagindex},{nsel:index!=Flagindex}]"
					:style="[selStyle]" :key="index" @tap="set_data_tab(index,item)">
					<image :src="item.path" class="styleImg" mode="widthFix"></image>
				</view>
			</view>
		</view>

		<view class="name_mess reference  mage10">
			参考图（选填）
			<view class="uploading" v-if="refPic==''" @click="uploadImage()">
				<image src="@/static/ai/sel.png" class="img" mode=""></image>

				<!-- <uni-file-picker  limit="1" title=""></uni-file-picker> -->
			</view>
			<view class="uploading" v-if="refPic!=''">
				<image :src="refPic" @click="uploadImage()" style="width: 160rpx;height: 160rpx;border-radius: 10rpx;"
					mode=""></image>
			</view>
		</view>
		<view class="Myno_class  mage10">
			<view class="Myno name_mess">
			<view class="name_mess display-between" >
				<view class="">	我不要（选填）</view> <view>{{reverseWords.length}}/10</view>
				</view>
			</view>
			<textarea maxlength='10' placeholder='请输入你不想要出现的元素' v-model="reverseWords" :style="[{'background':QianmenonlyBackgournd}]"
				style="padding: 10rpx; height: 80rpx;line-height: 80rpx; border-radius: 8rpx;color:#C9C6E8;margin:20rpx auto;width: 670rpx" @blur="bindTextAreaBlur" />
		</view>
		<view class="size_class name_mess mage10">
			<view class="chicun">
				尺寸
			</view>
			<!-- <image src="@/static/aipicture/zhuyi.png" mode="widthFix" style="margin-left: 16rpx;width: 15px;"></image> -->
		</view>
		<view class="size_mess mage10">
			<view class="size" @click="sizeClick(item.id)" v-for="(item,index) in sizeList">
				<view class="size_data"
					:style="item.id == proportionNum? 'border:3rpx solid #6958D5':'border:3rpx solid  #BFBFBF'">
					<view class="size_three" :style="getStyle(item,item.id, proportionNum)">
					</view>
				</view>
				<view class="size_word">
					<!-- 计算比例 -->
					{{aspectRatio(item.width,item.height)}}
				</view>
			</view>
		</view>
		<view class="sum_class mage10">
			<view class="name_mess">
				生成数量
			</view>
			<view class=" " style="font-size: 26rpx; font-weight: 500;color: #333333;">
				一次生成多张图片，超高性价比
			</view>

		</view>
		<view class="sum_box_data mage10">
			<view class="" v-for='(item,index) in sumList'>
				<view class="sum_dd" :class="[{sel:item.id == sumDataCurrent},{ nsel:item.id != sumDataCurrent}]"
					:key="index" @tap="set_sum_tab(index)">
					{{item.name}}
				</view>

			</view>
		</view>
		<view class="obottom">
			<view class="">
				消费:{{diamondNum}}
				<image src="@/static/aipicture/ai-diamond-icon.png" class="diamondIcon" mode="widthFix"></image>
			</view>
			<view class="open_botton " @click="create">
				<text>开始生成</text>
			</view>
		</view>
		<!-- <view class="open_botton mage10" @click="create" >
	<text>开始生成</text>
</view> -->
		<view style="height: 80rpx;"></view>
	</view>

</template>

<script>
	import {
		apiBaseUrl
	} from '@/config/config.js';
	export default {
		data() {
			return {
				describe: "", //描述
				refPic: "", //参考图
				reverseWords: "", //不想要什么
				proportion: 1, //尺寸
				sizeList: [],
				sumList: [{
						id: 1,
						name: 1
					},
					{
						id: 2,
						name: 2
					},
					{
						id: 3,
						name: 5
					},
				],
				datamassList: [{
						id: 1,
						name: '糖果缤纷',
						icon: '../../../static/index/level_1.png'
					},
					{
						id: 2,
						name: '都市恋人',
						icon: '../../../static/index/level_2.png'
					},
					{
						id: 3,
						name: '流光少年',
						icon: '../../../static/index/level_3.png'
					},
					{
						id: 4,
						name: '溢彩乐园',
						icon: '../../../static/index/level_4.png'
					}
				],
				showAiImg: false, //验证是否展示全部
				dataList: [],
				fgList: [],
				proportionNum: 1, //尺寸比例
				quantity: 1,
				diamondNum: 100, //钻石数量
				tabCurrent: 1,
				tabDataCurrent: 0,
				sumDataCurrent: 1, //数量

				selectColorSize: this.$store.state.selectColorSize, //字体颜色
				buttonBcak: this.$store.state.buttonBcak, //按钮颜色
				QianmenonlyBackgournd: this.$store.state.QianmenonlyBackgournd, //浅色
				ColorSize: this.$store.state.ColorSize, //字体颜色

				QianmenonlyBackgournd2: this.$store.state.QianmenonlyBackgournd2, //单个背景颜色深，现用户字体
				selectColorSize: this.$store.state.selectColorSize, //选中字体，现在用于 边框
				selStyle: {
					'--selectColorSize': this.$store.state.selectColorSize, //字体颜色
					'--buttonBcak': this.$store.state.buttonBcak, //按钮颜色
					'--borderSty': this.$store.state.borderSty, //选中背景线颜色
					'--QianmenonlyBackgournd': this.$store.state.QianmenonlyBackgournd, //单个背景颜色
					QianmenonlyBackgournd2: this.$store.state.QianmenonlyBackgournd2, //单个背景颜色
					'--QianmenonlyBackgournd': this.$store.state.QianmenonlyBackgournd, //单个背景颜色
					"--ColorSize": this.$store.state.ColorSize
				},
				Flagindex:0,
				aiEventId:"",//赛事id
				active:'',
				motifDescription:'',//主题描述
				themeImage:"",//主题图片
			}
		},
		computed: {
			listDataToShow() {
				if (this.showAiImg) {
					return this.dataList; // 如果showAiImg为true，则返回全部数据
				} else {
					return this.dataList.slice(0, 8); // 否则只返回前8条数据
				}
			}
		},
		onPullDownRefresh() {

			setTimeout(function() {
				uni.stopPullDownRefresh()
			}, 2000)
		},
		onLoad(val) {
			this.aiEventId=val.id
			this.type=val.type
			//风格
			this.getAI()

		},
		onShow() {
				this.getDetail()
		},
		methods: {
			getDetail() {
			  this.$api.aievent_detail({
			    id:this.aiEventId
			  }, (res) => {
				  ////1预约中，2正式报名，3投票中，4比赛结束
				  if(res.status){
					  this.themeImage= res.data.themeImage
					  this.active = res.data.evolveStatus
					  this.motifDescription=res.data.description
					  if(this.active==3 || this.active==4){
						  uni.redirectTo({
						  	url: '/pages/aipicture/finish/finish?id=' +this.aiEventId
						  })
						  	this.$common.errorToShow('报名时间已结束,不可生图');
					  }
				  }else{
					  	this.$common.errorToShow(res.message);
				  }
			  })
			},
			toggleShowAll() {
				this.showAiImg = !this.showAiImg;
			},
			// 计算宽高比例并返回格式为'x:y'的字符串
			aspectRatio(width, height) {
				if (!width || !height) return '未知';

				// 为了得到最简比例，我们可以使用最大公约数(GCD)来约分
				function gcd(a, b) {
					if (b === 0) return a;
					return gcd(b, a % b);
				}
				const widths = width;
				const heights = height;
				const gcdValue = gcd(width, height);
				// 返回格式化后的比例字符串
				return `${Math.floor(widths / gcdValue)}:${Math.floor(heights / gcdValue)}`;
			},
			getStyle: function(item, index, proportionNum) {
				let borderColor = index === proportionNum ? '#6958D5' : '#BFBFBF';
				return {
					width: item.width / 20 + 'rpx',
					height: item.height / 20 + 'rpx',
					border: '4rpx solid ' + borderColor,
					background: borderColor
				};
			},
			bindTextAreaBlur() {},
			create() {
				this.getDetail()
				if (this.describe == '') {
					this.$common.errorToShow('画面描述信息不能为空');
					return
				}
				// uni.navigateTo({
				// 	url:'/pages/aipicture/ai_create/ai_create'
				// })
				var tAmount = ''
				var quantity = ''
				if (this.sumDataCurrent == 1) {
					tAmount = '9.90'
					quantity = 1
				} else if (this.sumDataCurrent == 2) {
					tAmount = '19.80'
					quantity = 2
				} else if (this.sumDataCurrent == 3) {
					tAmount = '49.50'
					quantity = 5
				}
				var data = {
					payType: 7,
					quantity: quantity,
					totalAmount: tAmount,
					aiEventId:this.aiEventId,//'1808440244497879042'
				}
				
				var describeList=this.motifDescription+','+this.describe 
				
				if(this.reverseWords!=''){
					describeList=describeList+',我不要'+this.reverseWords
				}
				if(this.fgList!=''){
					describeList=describeList+','+this.fgList//.join(',')
				}
			
			
				var message = {
					describe:describeList,//描述加风格
					refPic: this.refPic,
					reverseWords: this.reverseWords,
					tAmount: tAmount,
					fgList: this.fgList,
					proportionNum: this.proportionNum,
					imageNumber:quantity,
				}
				this.$api.addSubmitAiOrder(data, res => {
					// 序列化对象
					let queryString = `data=${encodeURIComponent(JSON.stringify(res.data.data))}`;
					let messageString = `message=${encodeURIComponent(JSON.stringify(message))}`;
					if (res.status) {
						if(res.data.code==1 || res.data.code==2){
							this.$common.errorToShow(res.data.message);
							return
						}else{
							uni.navigateTo({
								url: `/pages/aipicture/ai_batch/ai_batch?${queryString}&${messageString}`
							})
						}
						
					}else{
						this.$common.errorToShow(res.data.message);
					}
				})

			},


			getAI() {
				this.$api.aigetStyle(res => {
					if (res.status) {
						this.dataList = res.data
					}
				})
				this.$api.aiGetScale(val => {
					if (val.status) {
						this.sizeList = val.data
					}
				})

			},
			sizeClick(val) {
				this.proportionNum = val
			},
			set_tab: function(id) {
				this.tabCurrent = id + 1
			},
			set_data_tab: function(id, val) {
				this.dataList[id].selectFlag = !this.dataList[id].selectFlag
				this.Flagindex=id
				this.fgList=val.style
				// const index = this.fgList.indexOf(val.style);
				// if (index !== -1) {
				// 	this.fgList.splice(index, 1);
				// } else {
				// 	this.fgList.push(val.style)
				// }
			},
			set_sum_tab: function(id) {
				this.sumDataCurrent = id + 1
				if (this.sumDataCurrent == 1) {
					this.diamondNum = '100'

				} else if (this.sumDataCurrent == 2) {
					this.diamondNum = '200'
				} else if (this.sumDataCurrent == 3) {
					this.diamondNum = '500'
				}

			},
			uploadImage() {
				let _this = this
				// this.photoType = type
				uni.chooseImage({
					success: (chooseImageRes) => {
						const tempFilePaths = chooseImageRes.tempFilePaths;
						let filePath = tempFilePaths[0]
						//#ifdef APP-IOS || APP-ANDROID
						const theme = uni.getStorageSync('theme');
						let color = theme == 'purple' ? "#000000" : "#ffffff"
						let style = theme == 'purple' ? "black" : "white"
						var styles = {
							color: color,
							background: "rgba(0,0,0,0.0)",
							style: style,
						}
						var waiting = plus.nativeUI.showWaiting("上传中...", styles);
						_this.uploadFile(filePath)
						//#endif
						// #ifndef APP-IOS || APP-ANDROID
						uni.showLoading({
							title: '上传中...'
						});
						_this.afterRead(tempFilePaths)
						// #endif
					}
				});
			},
			uploadFile(filePath) {
				var _this = this
				var url = apiBaseUrl + 'aievent/aiOrder/refPic?'+this.refPic
				let token = this.$db.get('userToken')
				uni.uploadFile({
					url: url, // 仅为示例，并非真实的接口地址
					filePath: filePath,
					fileType: 'image',
					name: 'file',
					header: {
						'Authorization': 'Bearer ' + token
					},
					success: (res) => {
						let data = JSON.parse(res.data);
						_this.refPic = data.data;
						//#ifdef APP-PLUS
						plus.nativeUI.closeWaiting();
						//#endif
						uni.hideLoading();
					},
					fail: (error) => {
						_this.$common.errorToShow(error)
						//#ifdef APP-PLUS
						plus.nativeUI.closeWaiting();
						//#endif
						uni.hideLoading();
					},
					complete: () => {
						//#ifdef APP-PLUS
						plus.nativeUI.closeWaiting();
						//#endif
						uni.hideLoading();
					}
				});
			},
			//压缩
			recursionCompressH5(url) {
				return new Promise((resolve, reject) => {
					this.recursionCompress(url, resolve)
				})
			},
			// 传入blob路径，.then()获取blob文件
			httpRequest(src) {
				let that = this
				return new Promise((resolve, reject) => {
					let xhr = new XMLHttpRequest()
					xhr.open('GET', src, true)
					xhr.responseType = 'blob'
					xhr.onload = function(e) {
						if (this.status == 200) {
							let myBlob = this.response
							let files = new window.File(
								[myBlob],
								myBlob.type, {
									type: myBlob.type
								}
							) // myBlob.type 自定义文件名
							resolve(files)
						} else {
							reject(false)
						}
					}
					xhr.send()
				})
			},
			recursionCompress(url, resolve) {
				let _this = this
				uni.getImageInfo({
					src: url,
					success(res) {
						let canvasWidth = res.width; //图片原始长宽
						let canvasHeight = res.height;
						let img = new Image();
						img.src = res.path;
						let canvas = document.createElement("canvas");
						let ctx = canvas.getContext("2d");
						canvas.width = canvasWidth / 2;
						canvas.height = canvasHeight / 2;
						ctx.drawImage(img, 0, 0, canvasWidth / 2, canvasHeight / 2);
						canvas.toBlob(function(fileSrc) {
							let imgSrc = window.URL.createObjectURL(fileSrc);
							uni.getFileInfo({
								filePath: imgSrc,
								success: (resFileInfo) => {
									if (resFileInfo.size > 1024 * 1024) {
										//压缩后大于1M就继续压缩
										console.log('再次压缩')
										_this.recursionCompress(imgSrc, resolve);
										// indexObj.recursionCompressH5(imgSrc, callback, item);
										return;
									} else {
										resolve(imgSrc)
									}
								},
							});
						});
					}
				});
			},
			afterRead(e) {
				let _this = this
				const file = e
				// 遍历图片资源
				file.map(item => {
					// 进行压缩图片
					this.recursionCompressH5(item).then(url => {
						_this.httpRequest(url).then(res => {
							const fileReader = new FileReader()
							fileReader.readAsDataURL(
								res
							) // 读取blob类型的图像文件（不是blob路径），读取成功触发onload方法，并得到result（base64格式的图片）
							fileReader.onload = (event) => {
								if (fileReader.result) {
									// 上传最终压缩之后的图片
									_this.uploadFile(fileReader.result).then(res => {
										// this.fileList.push(res)
									}).catch(() => {
										//#ifdef APP-PLUS
										plus.nativeUI.closeWaiting();
										//#endif
										uni.hideLoading();
									})
									// 调用wx_uploadImage接口，图片大小必须是1M以下，否则报错
									// wx_uploadImage({
									//   image: fileReader.result
									// }).then(res => {
									//   console.log('上传图片成功', res)
									//   this.image = res.storage_path
									// })
								}
							}
						})
					})
				})
			},
		}
	}
</script>

<style lang="scss" scoped>
	.mage10 {
		margin: 40rpx auto;
	}
   .statusbox {
			height: var(--status-bar-height);
		}
	/deep/.uni-textarea-placeholder {

		color: var(--QianmenonlyBackgournd) !important;
	}

	/deep/.uni-textarea-textarea {
		color: gray !important;
	}

	.pattern {
		width: 690rpx;
		height: 44rpx;
		font-size: 32rpx;
		font-weight: 500;
		color: #333333;
		line-height: 44rpx;
		margin: 30rpx auto;
		display: flex;
		justify-content: space-between;
	}
.display-between{
	width: 690rpx;	
	display: flex;
	justify-content: space-between;
}
	.switch_class {
		width: 690rpx;
		display: flex;
		justify-content: space-between;
		height: 60rpx;
		margin-top: 20rpx;

	}

	/deep/.uni-switch-input-checked {
		// background:#fff !important;
		// border:var(--borderSty) !important;
		border: 1px solid #dacfcd !important;
	}

	/deep/ .uni-switch-input.uni-switch-input-checked {
		background-color: #efd3ff;
	}

	/deep/.uni-switch-input:after {
		background: linear-gradient(-90deg, #6C58D5, #AA56D7) !important;

	}

	.name_mess {
		font-family: PingFang SC;
		font-weight: bold;
		font-size: 30rpx;
		color: #000000;
		opacity: 0.9;
	}

	.fengge {
		width: 690rpx;
		height: 32rpx;
		line-height: 32rpx;
		// margin: 20rpx auto;
	}

	.text_class {
		background: #F5F4FF;
		border-radius: 12rpx;
		padding: 20rpx;
		height: 250rpx;
		border-radius: 20rpx;
		color: #0000004d;
		margin: auto;
		width: 650rpx
	}

	.tab_box_data {
		// padding: 20rpx;
		width: 690rpx;
		// padding: 30rpx 70rpx 0;\
		display: flex;
		align-items: center;
		justify-content: space-between;

		.sel {

			//	color: var(--selectColorSize);
			background: linear-gradient(-90deg, #6C58D5, #AA56D7);
			font-weight: 600;
			color: white;
		}

		.nsel {
			font-weight: 400;
			border: 1px solid #714CD5;
			color: #714CD5;
		}

		.tab_dd {
			width: 150rpx;
			height: 56rpx;
			line-height: 50rpx;
			border-radius: 30rpx;
			// border: 1rpx solid #6958D5;
			font-size: 32rpx;
			text-align: center;
			margin-right: 15rpx;
			// border:var(--borderSty);
			// background-color:var(--borderSty);
			position: relative;
		}

	}

	.image_data {
		width: 699rpx;
		// margin: 20rpx auto;
		text-align: center;
		display: flex;
		flex-wrap: wrap;
		align-content: stretch;
	}

	.reference {
		width: 690rpx;
		// margin: 20rpx auto;
		line-height: 32rpx;
	}

	.uploading {
		background: #F5F4FF;
		border-radius: 10rpx;
		margin-top: 20rpx;
		width: 160rpx;
		height: 160rpx;
		line-height: 170rpx;
		text-align: center;

		.img {
			width: 50rpx;
			height: 50rpx;
		}
	}

	/deep/.file-picker__box {
		width: 160rpx !important;
		height: 160rpx !important;
	}

	.size_class {
		width: 690rpx;
		// margin: 20rpx auto;
		display: flex;
	}

	.Myno_class {
		width: 690rpx;
		// margin: 20rpx auto;
	}

	.Myno {
		width: 304rpx;
		height: 32rpx;
		line-height: 32rpx;
	}

	.chicun {
		width: 84rpx;
		height: 32rpx;
		font-size: 32rpx;

		font-weight: 500;
		color: #333333;
		line-height: 32rpx;
	}

	.size_mess {
		width: 690rpx;
		display: flex;
		// margin: 20rpx auto;
	}

	.size {
		margin-right: 40rpx;
		width: 100rpx;
		height: 100rpx;
	}

	.size_data {
		width: 91rpx;
		height: 91rpx;
		border-radius: 8rpx;
		display: flex;
		align-items: center;
	}


	.size_three {
		margin: 7rpx auto;
	}

	.size_word {
		width: 91rpx;
		text-align: center;
		height: 60rpx;
		line-height: 60rpx;

	}

	.sum_box_data {
		// padding: 20rpx;
		width: 690rpx;
		margin: 10rpx auto;
		// padding: 30rpx 70rpx 0;\
		display: flex;
		align-items: center;
		justify-content: space-between;

		.sel {
			border: 4rpx solid #6958D5;
			background: #F5F4FF;
			font-weight: 600;
			color: #6958D5;
		}

		.nsel {
			font-weight: 400;
			background: #F5F4FF;
		}

		.sum_dd {
			width: 156rpx;
			height: 62rpx;
			line-height: 62rpx;
			border-radius: 8rpx;
			// border: 1rpx solid #6958D5;
			font-size: 32rpx;
			text-align: center;
		}
	}

	.sum_class {
		display: flex;
		width: 690rpx;
		justify-content: space-between;
		margin: 10rpx auto;
		height: 70rpx;
		line-height: 70rpx;
	}

	.open_botton {
		// margin: 30rpx auto;
		width: 290rpx;
		height: 72rpx;
		background: linear-gradient(-90deg, #6C58D5, #AA56D7);
		text-align: center;
		border-radius: 42rpx;

		text {
			color: white;
			height: 72rpx;
			display: block;
			line-height: 70rpx;

		}
	}

	.image_bor {
		line-height: 530rpx;
		border-radius: 30rpx;
		width: 510rpx;
		height: 510rpx;
		margin: 50rpx auto;
		border: 3rpx solid #6958D5;
	}

	.obottom {
		display: flex;
		justify-content: space-between;
		align-items: center;
		width: 690rpx;
		margin: 40rpx auto;
		font-weight: bold;
		font-size: 30rpx;
	}

	.diamondIcon {
		width: 35rpx;
		 margin: 0 0 0 15rpx;

	}

	.style {
		display: flex;
		flex-wrap: wrap;
		justify-content: space-between;
		width: 690rpx;

		.styleImg {
			width: 133rpx;
		}

		.sel {
			width: 146rpx;
			text-align: center;
			padding-top: 6rpx;
			border-radius: 15rpx;
			height: 146rpx;
			margin-right: 20rpx;
			margin-top: 20rpx;
			background: linear-gradient(-90deg, #6C58D5, #AA56D7);

		}

		.nsel {
			padding-top: 6rpx;
			margin-right: 20rpx;
			margin-top: 20rpx;
			width: 146rpx;
			text-align: center;
			line-height: 142rpx;
			height: 146rpx;
		}
	}

	.styIcon {
		width: 35rpx;
		height: 35rpx;
		margin-left: 15rpx;
	}
</style>
